package category

import (
	"context"
	"mall/common/excption"
	constans "mall/services/product/rpc/consts"
	"mall/services/product/rpc/internal/domain/bo"
	"mall/services/product/rpc/internal/mapper"
	"mall/services/product/rpc/internal/mapper/entity"
	"time"

	"mall/services/product/rpc/internal/svc"
	"mall/services/product/rpc/pb"

	"github.com/zeromicro/go-zero/core/logx"
)

type SaveCategoryInfoLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSaveCategoryInfoLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SaveCategoryInfoLogic {
	return &SaveCategoryInfoLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *SaveCategoryInfoLogic) SaveCategoryInfo(in *pb.SaveCategoryInfoDTO) (*pb.SaveCategoryInfoVO, error) {
	// 1.check request dto
	categoryMapper, checkErr := l.checkRequestDTO(in)
	if checkErr != nil {
		return nil, checkErr
	}
	// 2.save db
	categoryId, saveErr := l.saveDB(in, categoryMapper)
	if saveErr != nil {
		return nil, saveErr
	}
	// 3.return obj
	return &pb.SaveCategoryInfoVO{CategoryId: categoryId}, nil
}

func (l *SaveCategoryInfoLogic) saveDB(in *pb.SaveCategoryInfoDTO, categoryMapper *mapper.CategoryMapper) (int64, error) {
	categoryEntity := entity.CategoryEntity{}
	categoryEntity.ShopId = in.ShopId
	categoryEntity.ParentId = in.ParentId
	categoryEntity.Name = in.Name
	categoryEntity.Desc = in.Desc
	categoryEntity.Path = in.Path
	categoryEntity.Icon = in.Icon
	categoryEntity.ImgUrl = in.ImgUrl
	categoryEntity.Level = int64(in.Level)
	categoryEntity.Seq = int64(in.Seq)
	categoryEntity.Status = constans.Normal
	now := time.Now()
	categoryEntity.CreateTime = now
	categoryEntity.UpdateTime = now
	categoryId, saveErr := categoryMapper.InsertCtx(l.svcCtx.DBEngin, categoryEntity)
	if saveErr != nil {
		return -1, saveErr
	}
	return categoryId, nil
}

func (l *SaveCategoryInfoLogic) checkRequestDTO(in *pb.SaveCategoryInfoDTO) (*mapper.CategoryMapper, error) {
	categoryMapper := mapper.NewCategoryMapper(l.ctx)
	categoryBO := bo.CategoryBO{Name: in.Name, ParentId: in.ParentId}
	selectCountCtx, checkErr := categoryMapper.SelectCountCtx(l.svcCtx.DBEngin, categoryBO)
	if checkErr != nil {
		return nil, checkErr
	}
	if selectCountCtx > 0 {
		return nil, excption.NewErrCode(constans.CategoryRepeatErr)
	}
	return categoryMapper, nil
}
